package com.belf.console.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.belf.common.config.MigrateConfig;
import com.belf.common.core.domain.AjaxResult;
import com.belf.common.utils.DateUtils;
import com.belf.console.agent.migrate.job.BuildDataSourceConf;
import com.belf.console.agent.migrate.job.ExecuteSqlTask;
import com.belf.console.domain.DataReportObject;
import com.belf.console.domain.DataSourceInfo;
import com.belf.console.domain.DataSqlTask;
import com.belf.console.domain.DataTaskConf;
import com.belf.console.mapper.DataSqlTaskMapper;
import com.belf.console.service.IDataSourceInfoService;
import com.belf.console.service.IDataSqlTaskService;
import com.belf.console.service.IDataTaskConfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.belf.common.core.domain.AjaxResult.DATA_TAG;

/**
 * SQL执行Service业务层处理
 * 
 * @author belf
 * @date 2024-08-03
 */
@Service
public class DataSqlTaskServiceImpl implements IDataSqlTaskService {

    private static final Logger logger = LoggerFactory.getLogger(DataSqlTaskServiceImpl.class.getName());

    @Autowired
    private DataSqlTaskMapper dataSqlTaskMapper;
    @Autowired
    private IDataSourceInfoService dataSourceInfoService;
    @Autowired
    private MigrateConfig migrateConfig;
    @Autowired
    private IDataTaskConfService dataTaskConfService;


    /**
     * 查询SQL执行
     * 
     * @param id SQL执行主键
     * @return SQL执行
     */
    @Override
    public DataSqlTask selectDataSqlTaskById(Long id)
    {
        return dataSqlTaskMapper.selectDataSqlTaskById(id);
    }

    @Override
    public long selectDataCount(DataSqlTask dataSqlTask) {
        return dataSqlTaskMapper.selectDataCount(dataSqlTask);
    }

    @Override
    public AjaxResult executeSql(DataSqlTask dataSqlTask) {
        if (dataSqlTask.getDatasourceId()!=null){
            String executeSql = dataSqlTask.getSqlContext();
            String databaseName = dataSqlTask.getDatabaseName();
            DataSourceInfo dataSourceInfo = dataSourceInfoService.selectDataSourceInfoById(dataSqlTask.getDatasourceId());
//            dataSourceInfoService.setDataSourceDatabase(dataSourceInfo,databaseName);
            dataSourceInfo.setExecuteSql(executeSql);
            // TODO 保存日志
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.executeSql(), dataSourceInfo);

            // 执行结果保存
//            dataSourceInfo.setExecuteResult(ajaxResult.get(DATA_TAG).toString());
            dataSqlTask.setExecuteResult(ajaxResult.get(DATA_TAG).toString());
            dataSqlTask.setDataSourceName(dataSourceInfo.getDataSourceName());
            insertDataSqlTask(dataSqlTask);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult convertSql(DataReportObject dataReportObject) {
        DataTaskConf task = dataTaskConfService.selectDataTaskConfById(dataReportObject.getTaskId());
       try {
           String sourceId = task.getSourceId();
           String sinkId = task.getSinkId();
           String[] ids = {sourceId, sinkId};
           List<DataSourceInfo> dataSourceList = dataSourceInfoService.selectDataSourceInfoByIds(ids);
           /*dataSourceList.forEach(dataSourceInfo -> {
               if (dataSourceInfo.getId().equals(sourceId)){
                   dataSourceInfoService.setDataSourceDatabase(dataSourceInfo, task.getSourceDatabase());
               }
               if (dataSourceInfo.getId().equals(sinkId)){
                   dataSourceInfoService.setDataSourceDatabase(dataSourceInfo, task.getSinkDatabase());
               }
           });*/
//           DataTaskConf taskData=new DataTaskConf();
           task.setDataSourceInfoList(dataSourceList);
           JSONObject params = new JSONObject();
           params.put("sql",dataReportObject.getSourceDdl());
           params.put("name",dataReportObject.getSourceObjectName());
           params.put("type",dataReportObject.getType());

           return ExecuteSqlTask.executeSql(migrateConfig.convertSql(),task, params);
       }catch (Exception e){
           logger.error(e.getMessage());
       }
       return AjaxResult.error();
    }

    /**
     * 查询SQL执行列表
     * 
     * @param dataSqlTask SQL执行
     * @return SQL执行
     */
    @Override
    public List<DataSqlTask> selectDataSqlTaskList(DataSqlTask dataSqlTask)
    {
        return dataSqlTaskMapper.selectDataSqlTaskList(dataSqlTask);
    }

    /**
     * 新增SQL执行
     * 
     * @param dataSqlTask SQL执行
     * @return 结果
     */
    @Override
    public int insertDataSqlTask(DataSqlTask dataSqlTask)
    {
        dataSqlTask.setCreateTime(DateUtils.getNowDate());
        dataSqlTask.setUpdateTime(DateUtils.getNowDate());
        return dataSqlTaskMapper.insertDataSqlTask(dataSqlTask);
    }

    /**
     * 修改SQL执行
     * 
     * @param dataSqlTask SQL执行
     * @return 结果
     */
    @Override
    public int updateDataSqlTask(DataSqlTask dataSqlTask)
    {
        dataSqlTask.setUpdateTime(DateUtils.getNowDate());
        return dataSqlTaskMapper.updateDataSqlTask(dataSqlTask);
    }

    /**
     * 批量删除SQL执行
     * 
     * @param ids 需要删除的SQL执行主键
     * @return 结果
     */
    @Override
    public int deleteDataSqlTaskByIds(Long[] ids)
    {
        return dataSqlTaskMapper.deleteDataSqlTaskByIds(ids);
    }

    /**
     * 删除SQL执行信息
     * 
     * @param id SQL执行主键
     * @return 结果
     */
    @Override
    public int deleteDataSqlTaskById(Long id)
    {
        return dataSqlTaskMapper.deleteDataSqlTaskById(id);
    }


}
